﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;

public class LuaManager : Manager<LuaManager>, IUpdate
{
    static LuaEnv luaEnv { get; set; }

    private Dictionary<string, string> LuaTxtMap = new Dictionary<string, string>();

    #region example
    public static void LuaGetMer()
    {
        luaEnv.FullGc();
        luaEnv.DoString("local me=require 'perf.memory'" +
                        "CS.LuaToolPage.Log(me.total())" +
                        "CS.LuaToolPage.Log(me.snapshot())", "LuaToolPage");
    }
    public static void LuaStartTime()
    {
        luaEnv.DoString("local profiler=require 'perf.profiler'" +
                        "profiler.start()", "LuaToolPage");
    }
    public static void LuaReportTime()
    {
        luaEnv.DoString("local profiler=require 'perf.profiler'" +
                        "CS.LuaToolPage.Log(profiler.report())", "LuaToolPage");
    }
    public static void LuaStopTime()
    {
        luaEnv.DoString("local profiler=require 'perf.profiler'" +
                        "profiler.stop()", "LuaToolPage");
    }
    #endregion

    public override void OnInit()
    {
    }
    public override void OnReset()
    {
    }
    public void InitGlobalLua(UnityEngine.Object[] tas)
    {
        luaEnv = new LuaEnv();
        LuaTxtMap.Clear();
        InitAssets(tas);
        InitLua(LuaTxtMap);
    }
    public void InitClassLua(UnityEngine.Object[] tas)
    {
        LuaTxtMap.Clear();
        InitAssets(tas);
    }
    public void InitAssets(UnityEngine.Object[] tas)
    {
        TextAsset textAsset;
        for (int i = 0,len = tas.Length; i < len; i++)
        {
            textAsset = tas[i] as TextAsset;
            try
            {
                if (textAsset == null) continue;
                LuaTxtMap.Add(textAsset.name.Split('.')[0], textAsset.text);
            }
            catch (Exception e)
            {
                GLog.Exception(e.Message);
            }
        }
    }
    private void InitLua(Dictionary<string, string> LuaTxtMap)
    {
        foreach (var item in LuaTxtMap)
        {
            luaEnv.DoString(item.Value,item.Key);
        }
    }
    public LuaTable NewTable()
    {
        return luaEnv == null ? null : luaEnv.NewTable();
    }
    public LuaTable GetTable(string name)
    {
        if (luaEnv == null) return null;
        LuaTable table;
        luaEnv.DoString(LuaTxtMap[name], name);
        luaEnv.Global.Get(name, out table);
        return table;
    }

    public void OnUpdate(float deltaTime)
    {
        if (luaEnv == null) return;
        luaEnv.Tick();
    }

    public void OnLateUpdate(float dt)
    {

    }
    public override void OnDestroy()
    {
        base.OnDestroy();
    }
}
